package com.virtualmall.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.virtualmall.bean.Product;
import com.virtualmall.common.Page;
import com.virtualmall.dao.ProductDao;

@Repository
public class ProductDaoImpl extends GenericDaoHibernateImpl<Product, Long> implements ProductDao {
	public ProductDaoImpl() {
		super(Product.class);
	}

	@SuppressWarnings("unchecked")
	public List<Product> getProductList(String keyword,Page page) {
	    String searchCondition = "";
	    if(StringUtils.isNotEmpty(keyword)){
	        searchCondition = "where p.productName like :keyword";
	    }
	    
		String hql = "select p.id as id,p.productName as productName,p.discountPrice as discountPrice,p.originalPrice as originalPrice" +
				",p.type as type,p.hot as hot,p.stock as stock,p.imagePath as imagePath " +
				"from Product p "+searchCondition+" order by p.updateDate desc,p.createDate desc";
		
        Query query = this.getCurrentSession().createQuery(hql)
                .setResultTransformer(Transformers.aliasToBean(Product.class));
        if(StringUtils.isNotEmpty(keyword)){
            query.setString("keyword", "%"+keyword+"%");
        }
        
        if (page != null) {
            query.setFirstResult((page.getCurrentPage() - 1)
                    * page.getPerPageSize());
            query.setMaxResults(page.getPerPageSize());
        }
        
		return (List<Product>)query.list();
	}

	public Long getProductListCount(String keyword) {
        String searchCondition = "";
        if(StringUtils.isNotEmpty(keyword)){
            searchCondition = "where p.productName like :keyword";
        }
        
		String hql = "select count(p.id) from Product p "+searchCondition;
		
		Query query = this.getCurrentSession().createQuery(hql);
        if(StringUtils.isNotEmpty(keyword)){
            query.setString("keyword", "%"+keyword+"%");
        }
		
		return (Long)query.uniqueResult();
	}
}
